var http = require('http'), url = require('url'), fs = require('fs');

var data = '<script>' + fs.readFileSync('bookmarklet.js') + '</script>';

http.createServer(function (req, res) {
	var q = url.parse(req.url,true).query;
	if (!q || !q.url) {
		res.writeHead(500, {'Content-Type': 'text/plain'});
		res.end('\n');
	} else {
		fetchAndRespond(q.url,res);
	}

}).listen(8124, "192.168.2.107");

function fetchAndRespond(q,res) {
	var x = url.parse(q);
	var host = x.host;
	var path = x.pathname || '/';
	
	var client = http.createClient(80,host);
	var req = client.request('GET', path, { host: host });
	req.end();
	var str = '';
	req.on('response', function(_res) {
		_res.setEncoding('utf8');
		_res.on('data', function(chunk) {
			str += chunk;
		});
		_res.on('end', function() {
			res.writeHead(200, {'Content-Type': 'text/html'});
			//			str += '<script>alert("doch");</script>';
			str += data;
			res.end(str + '\n');
		});
	});
}
console.log('Server running at http://127.0.0.1:8124/');

